package com.javasm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 0.1
 * @className: MyFilter1
 * @description:
 * @author: gfs
 * @date: 2025/6/25 10:59
 * @since: jdk17
 */
@WebFilter("/*")
public class MyFilter1 implements Filter {



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        /*
        * 1 请求编码
        * 2 允许跨域
        * */
        System.out.println("进入编码过滤器 跨域设置过滤器.......");
        /*如果需要对http协议报文数据做操作 一般需要强转*/
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //字符编码设置
        req.setCharacterEncoding("utf-8");
        //跨域设置
        /* 允许跨域的主机地址 */
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
        //resp.setHeader("Access-Control-Allow-Origin", "*");
        //resp.setHeader("Access-Control-Allow-Origin", "http://localhost:5174");
        /* 允许跨域的请求⽅法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        //调用链向后执行
        chain.doFilter(request,response);


    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }


}
